package cn.texous.easytalk.websocket.listener;

import cn.texous.easytalk.commonutil.constant.ResultCode;
import cn.texous.easytalk.commonutil.exception.BusinessException;
import cn.texous.easytalk.commonutil.model.redis.RedisMsg;
import cn.texous.easytalk.websocket.context.EtRedisMsgHandlerContext;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * insert description here
 *
 * @author Showa.L
 * @since 2019/5/28 16:10
 */
@Slf4j
@Component
public class EventMsgListener implements MessageListener {

    @Autowired
    private Gson gson;
    @Autowired
    private EtRedisMsgHandlerContext etRedisMsgHandlerContext;

    @Override
    public void onMessage(Message message, byte[] bytes) {
        log.info("received msg: {}", message);
        try {
            String msg = Optional.ofNullable(message)
                    .map(p -> p.toString())
                    .filter(p -> p.indexOf("type") > -1)
                    .orElseThrow(() -> new BusinessException(ResultCode.REDIS_MESSAGE_EMPTY_ERROR));
            RedisMsg redisMsgMessage = gson.fromJson(msg, RedisMsg.class);
            etRedisMsgHandlerContext.loadByType(redisMsgMessage.getType()).hander(redisMsgMessage);
        } catch (Exception e) {
            log.error(String.format("消息处理失败：%s", message), e);
        }
    }

}
